﻿using UnityEngine;
using System.Collections;

public class ShipCannon : MonoBehaviour {
	public bool playerControlled;
	public float fireRate;
	float lastFireTime;
	public GameObject BlasterFlash;
	public GameObject Blaster;
	public Vector3 blasterFlashOffset;
	public Vector3 projectileOffset;
	GameObject flash;

	void Start() {
		lastFireTime = Time.time + fireRate;
	}
	// Update is called once per frame
	void Update () {
		if(playerControlled) {
			if(Input.GetKeyDown(KeyCode.Space)) {
				flash = (GameObject)Instantiate (BlasterFlash, transform.position + blasterFlashOffset, Quaternion.identity);
				flash.GetComponent<Flash>().setDirection(new Vector3(0f, 0f, 0f));
				GameObject projectile = (GameObject)Instantiate(Blaster, transform.position + projectileOffset, Quaternion.identity);
				projectile.GetComponent<Blaster>().setDirection(1);
				projectile.layer = 10;
			}
		} else {
			if(Time.time - lastFireTime > 0f) {
				if(gameObject.GetComponent<EnemyShipFlight>().target != null) {
					if(gameObject.GetComponent<EnemyShipFlight>().target.GetComponent<Position>().rowPosition == RowPosition.FRONT && gameObject.GetComponent<EnemyShipFlight>().direction == ShipDirection.LOCKED) {
						flash = (GameObject)Instantiate (BlasterFlash, transform.position + blasterFlashOffset, Quaternion.identity);
						flash.GetComponent<Flash>().setDirection(new Vector3(0f, 0f, 180f));
						GameObject projectile = (GameObject)Instantiate(Blaster, transform.position + projectileOffset, Quaternion.identity);
						projectile.GetComponent<Blaster>().setDirection(-1);
						lastFireTime = Time.time + fireRate;
						projectile.layer = 9;
					}
				}
			}
		}
		if(flash != null) {
			flash.transform.position = new Vector3(flash.transform.position.x, transform.position.y, flash.transform.position.z);
		}
	}
}
